package com.luoran.system.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.luoran.common.core.utils.PrimaryKeyIdUtils;
import com.luoran.system.domain.PostEcharts;
import com.luoran.system.listener.PostDataListener;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.luoran.common.core.constant.UserConstants;
import com.luoran.common.core.utils.SecurityUtils;
import com.luoran.common.core.utils.poi.ExcelUtil;
import com.luoran.common.core.web.controller.BaseController;
import com.luoran.common.core.web.domain.AjaxResult;
import com.luoran.common.core.web.page.TableDataInfo;
import com.luoran.common.log.annotation.Log;
import com.luoran.common.log.enums.BusinessType;
import com.luoran.common.security.annotation.PreAuthorize;
import com.luoran.system.domain.SysPost;
import com.luoran.system.service.ISysPostService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 岗位信息操作处理
 *
 * @author guohailong
 */
@RestController
@RequestMapping("/post")
public class SysPostController extends BaseController {
    @Autowired
    private ISysPostService postService;

    @Autowired
    MinioClient minioClient;

    /**
     * 获取岗位列表
     */
    @PreAuthorize(hasPermi = "system:post:list")
    @GetMapping("/list")
    public TableDataInfo list(SysPost post) {
        startPage();
        List<SysPost> list = postService.selectPostList(post);
        return getDataTable(list);
    }

    @Log(title = "岗位管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:post:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPost post) throws IOException {
        List<SysPost> list = postService.selectPostList(post);
        ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
        util.exportExcel(response, list, "岗位数据");
    }

    /**
     * 根据岗位编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:post:query")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId) {
        return AjaxResult.success(postService.selectPostById(postId));
    }

    /**
     * 新增岗位
     */
    @PreAuthorize(hasPermi = "system:post:add")
    @Log(title = "岗位管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPost post) {
        if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
            return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
            return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        post.setPostId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        post.setCreateBy(SecurityUtils.getUsername());
        return toAjax(postService.insertPost(post));
    }

    /**
     * 修改岗位
     */
    @PreAuthorize(hasPermi = "system:post:edit")
    @Log(title = "岗位管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPost post) {
        if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
            return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
            return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        post.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(postService.updatePost(post));
    }

    /**
     * 删除岗位
     */
    @PreAuthorize(hasPermi = "system:post:remove")
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds) {
        return toAjax(postService.deletePostByIds(postIds));
    }

    /**
     * 获取岗位选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<SysPost> posts = postService.selectPostAll();
        return AjaxResult.success(posts);
    }

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        String fileName= UUID.randomUUID()+"_"+file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs
                    .builder()
                    .object(fileName)
                    .bucket("imgs")
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());

            return AjaxResult.success("http://localhost:9000/imgs/"+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    @GetMapping("/outLIst")
    public void outLIst(HttpServletResponse response) throws IOException {
        //指定类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        List<SysPost> sysPosts = postService.selectPostAll();
        String fileName = URLEncoder.encode("岗位", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(), SysPost.class).sheet("模板").doWrite(sysPosts);

    }

    @PostMapping("inList")
    public void inList(MultipartFile file) throws IOException {

        System.out.println(file.getResource());
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(file.getInputStream(), SysPost.class, new PostDataListener(postService)).sheet().doRead();

    }

    @GetMapping("getEcharts")
    public AjaxResult getEcharts(){

        List<PostEcharts> list=postService.getEcharts();


        return AjaxResult.success(JSON.toJSONString(list));
    }

}
